<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有                                 |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: anguolei@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//

namespace AuctionCore\AuctionOrder;

use AuctionCore\CarResource\CarModel;
use AuctionCore\Account\Back\Employee;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionCore\CarResource\BreachCar;
use AuctionCore\CarResource\SelfReceiveCar;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\AntNest\UserCenter;

/**
 * 过户模块模型
 * @author angl
 */
class Transfer
{

    private $order_id = null;

    /**
     * Transfer constructor.
     * @param int $order_id
     */
    public function __construct($order_id)
    {
        $this->order_id = $order_id;
    }

    /**
     * 添加过户信息
     * @param $order_id
     * @param $dealer_id
     * @param emp_id $
     * @param int $result
     * @param string $remark
     * @return mixed
     */
    public static function create($order_id, $dealer_id, $emp_id, $result = 0, $remark = '')
    {
        if ($order_id < 1 || $dealer_id < 1 || $emp_id < 1) return false;
        return M("transfer_log")->add([
            'order_id' => intval($order_id),
            'dealer_id' => intval($dealer_id),
            'emp_id' => intval($emp_id),
            'result' => intval($result),
            'remark' => $remark
        ]);
    }

    /**
     * @param $data
     * @return bool
     */
    public function update($data)
    {
        if (isset($data['order_id'])) unset($data['order_id']);
        $res = M("transfer_log")->where(['order_id' => $this->order_id])->save($data);
        return $res;
    }

    /**
     * 过户列表
     * @param int $page
     * @param int $size
     * @param array $params
     * @return array $result
     */
    public static function transfer_list($page = 1, $size = 10, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $size = (int)$size < 1 ? 10 : (int)$size;
        $map = self::make_transfer_params($params);
        $prefix = C('DB_PREFIX');
        //要查询的列
        $cols = "o.order_id,o.order_no,o.status,o.is_lock,o.car_id,c.car_id,c.plate_prefix,c.plate_suffix,c.car_no,c.brand_id,c.series_id,c.model_id,c.location_area,
                co.seller_name,co.deliver_id,co.phone,co.comefrom,co.comefrom_url,da.dealer_id,
                cd.contact_person,du.uid";
        $order = "o.last_time DESC";
        if ($params['status'] == 2) {
            $cols .= ',l.last_update as transfer_start_time';
        } elseif ($params['status'] == 3) {
            $cols .= ',l.last_update as transfer_success_time';
        } elseif (($params['status'] == 4)) {
            $cols .= ',l.last_update as transfer_fail_time';
        }

        $total = M('order')->alias('o')->field($cols)
            ->join($prefix . "car_dealer as cd ON cd.dealer_id = o.success_dealer_id")
            ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
            ->join($prefix . "cars as c ON c.car_id=o.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id=c.owner_id")
            ->join("LEFT JOIN " . $prefix . "transfer_log as l ON l.order_id=o.order_id")
            ->where($map)->count();

        $list = M('order')->alias('o')->field($cols)
            ->join($prefix . "car_dealer as cd ON cd.dealer_id = o.success_dealer_id")
            ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
            ->join($prefix . "cars as c ON c.car_id=o.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id=c.owner_id")
            ->join("LEFT JOIN " . $prefix . "transfer_log as l ON l.order_id=o.order_id")
            ->where($map)->limit($size)->page($page)->order($order)->select();
        if(!empty($list)){
            $dealer = new Dealer();
            $list = $dealer->get_contact_mobile_byAntNest($list);
        }
        $cm = new CarModel();
        $addr = new \AuctionCore\Other\Address();
        foreach ($list as $key => $val) {
            $list[$key] = $val;
            if ($params['auth']) {
                $deliver = Employee::user_info_id($val['deliver_id']);
                $list[$key]['deliver_name'] = $deliver['real_name'];
            }
            $brand = $cm->get_model_by_id($val['brand_id'], 'brand');
            $series = $cm->get_model_by_id($val['series_id'], 'series');
            $model = $cm->get_model_by_id($val['model_id']);
            $issue_params = [
                'order_id' => $val['order_id']
            ];
            if ($val['status'] == 9) {
                $issue_params['issue_type'] = 3;
            } elseif ($val['status'] == 10) {
                $issue_params['issue_type'] = 5;
            }
            $list[$key]['plate_number'] = C("PLATE_PREFIX." . $val['plate_prefix']) . $val['plate_suffix'];
            $list[$key]['bc_city_name'] = $addr->get_name_by_code($val['location_area']);
            $list[$key]['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
            //是否显示违约
            $list[$key]['is_again_void'] = true;
            // $changeInfo = changeOrder::detailMap(['order_id'=>$val['order_id'],'order_status'=>$val['status']]);
            // if ($changeInfo) {
            //     $list[$key]['is_again_void'] = false;
            // }
            if ($val['is_lock'] == 1) {
                $list[$key]['is_again_void'] = false;
            }
            //是否显示争议
            $list[$key]['is_show_dispute'] = true;
            if ($val['is_lock'] == 1) {
                $list[$key]['is_show_dispute'] = false;
            }
            $disInfo = M('dispute')->where(['order_id'=>$val['order_id'],'order_status'=>$val['status'],'od_type'=>1])->find();
            if ($disInfo) {
                $list[$key]['is_show_dispute'] = false;
            }
        }
        //dump($list);
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**
     * 过户列表参数过滤
     * @param $params
     * @return array
     */
    private static function make_transfer_params($params)
    {
        $map = array();
        //拍单状态
        if (!$params['auth']) {
            $map['co.deliver_id'] = $params['emp_id'];
        }
        if ($params['status'] == 1) {
            $map['l.result'] = array(array('eq', 0), array('EXP', 'IS NULL'), 'or');
            $map['o.status'] = array('eq', 9);
        }
        if ($params['status'] == 2) {
            $map['o.status'] = array('eq', 10); //过户中
            $map['l.result'] = array('eq', 1);
        }
        if ($params['status'] == 3) {
            //$map['o.status'] = array('eq', 11); //过户完成，待付尾款
            $map['l.result'] = array('eq', 2);
        }
        if ($params['status'] == 4) {
            $map['l.result'] = array('eq', 3);
        }
        //过户时间
        if (!empty($params['start_time']) || !empty($params['end_time'])) {
            if (empty($params['start_time'])) {
                $map['l.last_update'] = array("elt", $params['end_time'] . " 23:59:59");
            } elseif (empty($params['end_time'])) {
                $map['l.last_update'] = array("egt", $params['start_time'] . " 00:00:00");
            } else {
                $map['l.last_update'] = array(array("egt", $params['start_time'] . " 00:00:00"), array("elt", $params['end_time'] . " 23:59:59 "));
            }
        }
        if (!empty($params['bc_city'])) {
            $map['c.location_area'] = array("in", $params['bc_city']);
        }

        //拍单号
        if (!empty($params['order_no'])) {
            $map['o.order_no'] = $params['order_no'];
        }

        //车商联系人
        if (!empty($params['contact_person'])) {
            $map['cd.contact_person'] = $params['contact_person'];
        }
        //车商电话
        if (!empty($params['contact_mobile'])) {
            $uc = new UserCenter();
            $info1 = $uc->info_bymobile($params['contact_mobile'],2,1);
            $map['du.uid'] = array('eq',$info1['account_id']);
        }
        //车牌号
        if ($params['car_plate_number']) {
            $car_plate_number = trim($params['car_plate_number']);
            $car_plate_number_first = mb_substr($car_plate_number, 0, 1, 'UTF8');
            $car_plate_number_last = mb_substr($car_plate_number, 1, 7, 'UTF8');
            $plate_prefix = array_search($car_plate_number_first, C('PLATE_PREFIX'));
            $plate_suffix = substr($car_plate_number, 1);
            $map['c.plate_prefix'] = array('eq', $plate_prefix);
            if ($car_plate_number_last) {
                $map['c.plate_suffix'] = array('LIKE', '%' . $car_plate_number_last . '%');
            }
        }
        return $map;
    }

    //TODO 得到订单过户列表，不是拍单
    public static function getOrderList($page = 1, $size = 10, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $size = (int)$size < 1 ? 10 : (int)$size;
        $map = self::makeOrderTransferParams($params);
        $prefix = C('DB_PREFIX');
        //要查询的列
        $cols = "o.order_id,o.order_no,o. STATUS,o.is_lock,o.car_id,o.refer,
            c.car_id,c.plate_prefix,c.plate_suffix,c.car_no,c.brand_id,c.series_id,c.model_id,c.location_area,
            co.comefrom,co.comefrom_url";
			//bc.dealer_name as contact_person,bc.dealer_phone as contact_mobile,co.comefrom,co.comefrom_url";
        $order = "o.last_time DESC";
        if ($params['status'] == 2) {
            $cols .= ',l.last_update as transfer_start_time';
        } elseif ($params['status'] == 3) {
            $cols .= ',l.last_update as transfer_success_time';
        } elseif (($params['status'] == 4)) {
            $cols .= ',l.last_update as transfer_fail_time';
        }

        $total = M('order')->alias('o')->field($cols)
            ->join($prefix . "cars as c ON c.car_id = o.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id = c.owner_id")
            //->join('LEFT JOIN ' . $prefix . "breach_car as bc ON o.order_id = bc.d_order_id")
            ->join("LEFT JOIN " . $prefix . "transfer_log as l ON l.order_id=o.order_id")
            ->where($map)->count();

        $list = M('order')->alias('o')->field($cols)
            ->join($prefix . "cars as c ON c.car_id = o.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id = c.owner_id")
            //->join('LEFT JOIN ' . $prefix . "breach_car as bc ON o.order_id = bc.d_order_id")
            ->join("LEFT JOIN " . $prefix . "transfer_log as l ON l.order_id=o.order_id")
            ->where($map)
	        ->limit($size)
	        ->page($page)
	        ->order($order)
	        ->select();
        $cm = new CarModel();
        $addr = new \AuctionCore\Other\Address();
        foreach ($list as $key => $val) {
            $list[$key] = $val;
            if ($params['auth']) {
                $deliver = Employee::user_info_id($val['deliver_id']);
                $list[$key]['deliver_name'] = $deliver['real_name'];
            }
            $brand = $cm->get_model_by_id($val['brand_id'], 'brand');
            $series = $cm->get_model_by_id($val['series_id'], 'series');
            $model = $cm->get_model_by_id($val['model_id']);
            $issue_params = [
                'order_id' => $val['order_id']
            ];
            if ($val['status'] == 9) {
                $issue_params['issue_type'] = 3;
            } elseif ($val['status'] == 10) {
                $issue_params['issue_type'] = 5;
            }
            $refer = $val['refer'];
	        $orderId = $val['order_id'];
	        if($refer == 1){ //违约车辆
				$dealerData = BreachCar::getInfoByOtherOrderId($orderId);
	        }else{ //自收车辆
		        $dealerData = SelfReceiveCar::getInfoByOtherOrderId($orderId);
	        }
	        $list[$key]['contact_person'] = $dealerData['dealer_name']; //车商联系人
	        $list[$key]['contact_mobile'] = $dealerData['dealer_phone']; //车商电话

            $list[$key]['plate_number'] = C("PLATE_PREFIX." . $val['plate_prefix']) . $val['plate_suffix'];
            $list[$key]['bc_city_name'] = $addr->get_name_by_code($val['location_area']);
            $list[$key]['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        }
        //dump($list);
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    //TODO 订单过户列表，参数过滤
    private static function makeOrderTransferParams($params)
    {
        $map = array();

        $map['o.is_other_channel_deal'] = array('eq', 1); //表示其他渠道成交生成的订单
        //拍单状态
        if (!$params['auth']) {
            $map['co.deliver_id'] = $params['emp_id'];
        }
        if ($params['status'] == 1) {
            $map['l.result'] = array(array('eq', 0), array('EXP', 'IS NULL'), 'or');
            $map['o.status'] = array('eq', 9);
        }
        if ($params['status'] == 2) {
            $map['o.status'] = array('eq', 10); //过户中
            $map['l.result'] = array('eq', 1);
        }
        if ($params['status'] == 3) {
            //$map['o.status'] = array('eq', 11); //过户完成，待付尾款
            $map['l.result'] = array('eq', 2);
        }
        if ($params['status'] == 4) {
            $map['l.result'] = array('eq', 3);
        }
        //过户时间
        if (!empty($params['start_time']) || !empty($params['end_time'])) {
            if (empty($params['start_time'])) {
                $map['l.last_update'] = array("elt", $params['end_time'] . " 23:59:59");
            } elseif (empty($params['end_time'])) {
                $map['l.last_update'] = array("egt", $params['start_time'] . " 00:00:00");
            } else {
                $map['l.last_update'] = array(array("egt", $params['start_time'] . " 00:00:00"), array("elt", $params['end_time'] . " 23:59:59 "));
            }
        }
        if (!empty($params['bc_city'])) {
            $map['c.location_area'] = array("in", $params['bc_city']);
        }

        //拍单号
        if (!empty($params['order_no'])) {
            $map['o.order_no'] = $params['order_no'];
        }

        //车商联系人
        if (!empty($params['contact_person'])) {
            $map['bc.dealer_name'] = $params['contact_person'];
        }
        //车商电话
        if (!empty($params['contact_mobile'])) {
            $uc = new UserCenter();
            $info1 = $uc->info_bymobile($params['contact_mobile'],2,1);
            $map['du.uid'] = $info1['account_id'];
            //$map['bc.dealer_phone'] = $params['contact_mobile'];
        }
        //车牌号
        if ($params['car_plate_number']) {
            $car_plate_number = trim($params['car_plate_number']);
            $car_plate_number_first = mb_substr($car_plate_number, 0, 1, 'UTF8');
            $car_plate_number_last = mb_substr($car_plate_number, 1, 7, 'UTF8');
            $plate_prefix = array_search($car_plate_number_first, C('PLATE_PREFIX'));
            $plate_suffix = substr($car_plate_number, 1);
            $map['c.plate_prefix'] = array('eq', $plate_prefix);
            if ($car_plate_number_last) {
                $map['c.plate_suffix'] = array('LIKE', '%' . $car_plate_number_last . '%');
            }
        }
        return $map;
    }

    /**
     * 获取过户详情
     * @param $order_id
     * @return mixed
     */
    public static function getTransferByOrderId($order_id)
    {
        return M("transfer_log")->where(['order_id' => $order_id])->find();
    }

    /**
     * 获取过户日志对应的结果日志
     */
    public static function get_transfer_log($map = [])
    {
        if (empty($map)) {
            return false;
        }
        return M("transfer_log")->where($map)->find();
    }
}

//end
